<?php
/*
---------------------------------------------------------
														+
名称:易通支付通道										+
														+
控制器名称:YiTongController								+
														+
日期:2017-10-11											+
														+
作者:小翁												+
														+
---------------------------------------------------------
*/
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;

class JusenController extends PayController{
    protected $config;
    protected $key;
    protected $url;
	protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);
        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }
		
        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));
        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        $data = array();
        $data['merCode'] = $this->config['mch_id'];
        //业务订单号
        $data['tranNo'] = $return['orderid'];
        //交易金额
        $data['tranAmt'] = strval(intval($return['amount'] * 100));
        $data['settleType'] = "0";
        switch($product['paytype']){
            //微信
            case 1:
                $data['collectWay'] = 'WXZF';
                break;
            //支付宝
            case 3:
                $data['collectWay'] = 'ZFBZF';
                break;
            //QQ钱包扫码
            case 8:
                $data['collectWay'] = 'QQZF';
                break;
            //银联扫码
            case 11:
                $data['collectWay'] = 'UPZF';
                break;
                //京东钱包
            case 9:
                $data['collectWay'] = 'JDZF';
                break;
            //QQ钱包H5
            case 10:
                $data['collectWay'] = 'QQWEP';
                break;
            //银联快捷
            case 13:
                $data['collectWay'] = 'QQWEP';
                break;
                //支付宝H5
            case 4:
                $data['collectWay'] = 'APAY';
                $this->config['gateway'] = 'http://202.61.87.38:8080/trans/gateway/pay/wap';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);

        }
        $data['tranTime'] = date("YmdHis",time());
        $data['expireTime'] = strval(120);
        //回调地址
        $data['noticeUrl'] = $return['notifyurl'];
        $data['subject'] = 'pay';
        $data['orderDesc'] = 'pay';

        ksort($data);

        $str = httpstr($data).$this->config['signkey'];
        $data['sign'] = md5($str);

        $t = array("jsonParam"=>json_encode($data));
        //po($this->config['gateway'], $t);

        //po($this->config['gateway'], $data);

        $res = $this->curl($this->config['gateway'], json_encode($data));
        //echo $res."<br/>";

        if(!$res){
            $this->showmessage('请求失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }
        //保存请求返回
        M("Order")->where([ 'pay_orderid'=>$return['orderid']])->save(["rd_return"=>$res,"request"=>json_encode($data)]);

        $res = json_decode($res, true);
        if(empty($res)){
            $this->showmessage("数据获取错误",['code'=>C("THIRDCODES.".$this->class)]);
        }

        /*
         * Array
            (
                [URL] => https://qr.alipay.com/bax09341dubwq1cswp9k00d0
                [respCode] =>
                [respMsg] =>
                [sign] => 321313b6a8f62ed40b1d77c8adf477c2
                [tranNo] => 201808201855598408552
            )
         */
        $code = $res['URL'];

        if(!$code){
            $this->showmessage("获取二维码失败",['code'=>C("THIRDCODES.".$this->class)]);
        }

        switch($product['paytype']){
            //支付宝H5
            case 4:
                header("location: {$code}");exit;
            default:
        }

        $paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?data=".urlencode($code));
        $this->display("WeiXin/Pay");
    }

    function curl($apiurl,$data){
        $con = curl_init($apiurl);
        curl_setopt($con, CURLOPT_HEADER, false);
        curl_setopt($con, CURLOPT_POSTFIELDS, $data);
        curl_setopt($con, CURLOPT_POST, true);
        curl_setopt($con, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($con, CURLOPT_TIMEOUT, 10);
        curl_setopt($con, CURLOPT_HTTPHEADER,  array(
            "Content-type: application/json;charset='utf-8'",
            "Accept: application/json",
            "Cache-Control: no-cache",
            "Pragma: no-cache",
        ));
        $res = curl_exec($con);
        curl_close($con);

        return $res;
    }

    //通知
    public function notifyurl(){
       //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
       //file_put_contents("a.txt",var_export($_GET,true."\r\n\r\n"), FILE_APPEND);
       //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
       //file_put_contents("a.txt", date('Y-m-d H:i:s',time())."\r\n\r\n", FILE_APPEND);

        $s = file_get_contents('php://input');

        //$s = '{"respCode":"0","respMsg":"交易成功","settleDate":"20180820","sign":"a17bcd9ae5701ae12a3c6731b3c8dff3","tranAmt":"1000","tranNo":"201808201913354099477"}';
        $p = $data = json_decode($s, true);
        if(!$p || empty($p)){
            exit;
        }
        //echo '<pre/>'; print_r($p);exit;
        /*
         * Array
            (
                [respCode] => 0
                [respMsg] => 交易成功
                [settleDate] => 20180820
                [sign] => a17bcd9ae5701ae12a3c6731b3c8dff3
                [tranAmt] => 1000
                [tranNo] => 201808201913354099477
            )
         */

        //获取订单信息
        $orderid = $p['tranNo'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();

        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$p['busi_order_no']))->save(array("server_return"=> $s));
        Order::getInstance()->edit($find['id'],array("server_return"=> $s));
        Ordermember::getInstance(getIdByBianHao($find['pay_memberid']))->edit($find['id'],array("server_return"=> $s));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>'Jusen'))->find();

        if($p['respCode'] != 0){
            echo "pail_fail"; exit;
        }

        $sign = $p['sign'];
        unset($p['sign']);

        ksort($p);
        $str = httpstr($p).$this->config['signkey'];
        $sign2 = md5($str);

        //echo 'sign: '.$sign.'<br/>';
        //echo 'sign2:'.$sign2;exit;

        if($sign != $sign2){
            exit("fail");
        }

        //处理支付
        $this->EditMoney($find['pay_orderid'],"Jusen",0);
        //回调成功
        echo '000000'; exit;
    }

    public function callBackUrl(){

        echo '支付成功'; exit;
    }
}